package ch.fhnw.qualiscan.application.views;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.controllers.Dashboard;
import ch.fhnw.qualiscan.application.modals.AddQuestionnaire;
import ch.fhnw.qualiscan.application.modals.DeleteQuestionnaire;
import ch.fhnw.qualiscan.core.View;
import ch.fhnw.qualiscan.core.db.helpers.dashboardTableArgs;
import ch.fhnw.qualiscan.core.db.pojos.Questionnaire;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class DashboardView extends View {
	
	private Dashboard controller;
	private DashboardView dashboardView;
	
	public DashboardView(Dashboard dashboard) {
		this.dashboardView = this;
		this.controller = dashboard;
	}

	private VerticalLayout dashboardWrap;
	private Label title;

	private VerticalLayout tabLayout1;
	private VerticalLayout tabLayout2;
	private VerticalLayout tabLayout3;
	
	
	//Dashboard Tab1
	private Table surveyTable;
	
	//Dashboard Tab3
	private Table questionnaireTable;
	
	@Override
	public void initComponents() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void buildLayout() {
		
		dashboardWrap = new VerticalLayout();
		dashboardWrap.setMargin(false, false, true, false);
		dashboardWrap.setSpacing(true);
		
		title = textHelper.h1(TM.get("dashboard.title"));
		dashboardWrap.addComponent(title);
		
		addComponent(dashboardWrap);
		
		tabSheet.addTab(buildTabLayout1(), TM.get("dashboard.tab1.title"), null);
		tabSheet.addTab(buildTabLayout2(), TM.get("dashboard.tab2.title"), null);
		tabSheet.addTab(buildTabLayout3(), "Questionnaires", null);
		
		addComponent(tabSheet);
		
		
	}
	
	private VerticalLayout buildTabLayout3() {
		   tabLayout3 = new VerticalLayout();
		   tabLayout3.setMargin(true);
		        
		        HorizontalLayout addDomainForm = new HorizontalLayout();
			addDomainForm.setMargin(true, true, true, false);
			Button addButton =  new Button(TM.get("action.add"), new Button.ClickListener() {
		            public void buttonClick(Button.ClickEvent event) {
		                openModal(new AddQuestionnaire((DashboardView)event.getButton().getData(), controller.userSessionHelper.getUser()));
		            }
		        });
		        
		    addButton.setIcon(Config.ICON_ADD);
		    addButton.setData(this);    
			addDomainForm.addComponent(addButton);
			tabLayout3.addComponent(addDomainForm);
		        
		        
		    questionnaireTable = new Table();
		    questionnaireTable.setWidth("100%");
			questionnaireTable.setPageLength(0);
			questionnaireTable.setSelectable(true);
		    questionnaireTable.setImmediate(true);
		        
		        // generate buttons
		    questionnaireTable.addGeneratedColumn("gen_edit", new Table.ColumnGenerator() {
		                public Component generateCell(Table source, Object itemId, Object columnId) {
		                        final Questionnaire thisQuestionnaire = (Questionnaire) source.getContainerProperty(itemId, "questionnaire").getValue();
		                        Button b = new Button(TM.get("action.edit"));
		                        b.setData(thisQuestionnaire.getId());
		                        
		                        b.addListener(new Button.ClickListener() {
		                            
		                            public void buttonClick(ClickEvent event) {
		                                int selectedQuestionnaireId = thisQuestionnaire.getId();
		                                Questionnaire selectedQuestionnaire = controller.getQuestionnaireModel().getQuestionnaire(selectedQuestionnaireId);
		                                if(selectedQuestionnaire != null) {
		                                    controller.loadQuestionnairePage(selectedQuestionnaire);
		                                } else {
		                                    System.out.append("error... selectedQuestionnaireId: " + selectedQuestionnaireId);
		                                }
		                            }
		                        });	
		                        b.setIcon(Config.ICON_EDIT);
		                        return b;
		                }
		        });

		        questionnaireTable.addGeneratedColumn("gen_delete", new Table.ColumnGenerator() {
		                public Component generateCell(Table source, final Object itemId, Object columnId) {
		                        final Questionnaire thisQuestionnaire = (Questionnaire) source.getContainerProperty(itemId, "questionnaire").getValue();
		                        Button b = new Button(TM.get("action.delete"));
		                        b.setData(thisQuestionnaire.getId());
		                        
		                        b.addListener(new Button.ClickListener() {
		                            public void buttonClick(ClickEvent event) {
		                                
		                                Questionnaire selectedQuestionnaire = controller.getQuestionnaireModel().getQuestionnaire(thisQuestionnaire.getId());
		                                if(selectedQuestionnaire != null) {
		                                    openModal(new DeleteQuestionnaire(selectedQuestionnaire, dashboardView));
		                                   
		                                } else {
		                                    //System.out.append("error... selectedQuestionnaireId: " + thisQuestionnaire.getId());
		                                }
		                            }
		                        });
		                        
		                        b.setIcon(Config.ICON_DELETE);
		                        return b;
		                }
		        });
		        
		        questionnaireTable.setContainerDataSource(controller.getQuestionaireData());

		        questionnaireTable.setColumnHeader("title", TM.get("questionnaire.title"));
		        questionnaireTable.setColumnHeader("desc", TM.get("questionnaire.desc"));
		        questionnaireTable.setColumnHeader("createdAt", TM.get("questionnaire.created"));
		        questionnaireTable.setColumnHeader("gen_edit", TM.get("action.edit"));
		        questionnaireTable.setColumnHeader("gen_delete", TM.get("action.delete"));

		        questionnaireTable.setVisibleColumns(
		            new Object[]{
		                "title", 
		                "desc", 
		                "createdAt", 
		                "gen_edit", 
		                "gen_delete"
		            }
		        );
		        
		     
		        tabLayout3.addComponent(questionnaireTable);
		        return tabLayout3;
	}
	

	private VerticalLayout buildTabLayout1() {
		tabLayout1 = new VerticalLayout();
		
		VerticalLayout tableWrapper = new VerticalLayout();
		tableWrapper.setSpacing(true);
		tableWrapper.setMargin(true);
		
		if(controller.getTableContainer().size() > 0) {
			tableWrapper.addComponent(textHelper.p(TM.get("dashboard.tab1.desc1")));
			// add table to tableWrapper
			tableWrapper.addComponent(buildTable());
		} else {
			tableWrapper.addComponent(textHelper.p(TM.get("dashboard.tab1.desc2")));
		}
		
		tabLayout1.addComponent(tableWrapper);
		
		
		return tabLayout1;
	}
	
	private VerticalLayout buildTabLayout2() {
		tabLayout2 = new VerticalLayout();
		
		tabLayout2.setMargin(true);
		tabLayout2.setSpacing(true);
		
		tabLayout2.addComponent(textHelper.p(TM.get("dashboard.tab2.desc")));
		
		Button newSurvey = new Button(TM.get("dashboard.tab2.button"));
		newSurvey.addListener(new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
                                controller.getAppData().getLoaderLib().setUrl("NewSurvey/0/");
				event.getButton().setEnabled(false);
			}
		});
		newSurvey.setIcon(Config.ICON_ADD);
		
		tabLayout2.addComponent(newSurvey);
		
		return tabLayout2;
	}
	
	
	public Table buildTable() {
		surveyTable = new Table();
		surveyTable.setWidth("100%");
		surveyTable.setPageLength(0);
		surveyTable.setSelectable(false);
		
		/*
		 * Generated Column for Button
		 */
		surveyTable.addGeneratedColumn("surveyEditButton", new Table.ColumnGenerator() {
			public Component generateCell(Table source, Object itemId, Object columnId) {
				HorizontalLayout buttonBar = new HorizontalLayout();
				buttonBar.setSpacing(true);
				
				final SurveyUserRole sur = (SurveyUserRole) source.getContainerProperty(itemId, "sur").getValue();
				
				// edit button
				Button editButton = new Button(TM.get("action.edit"));
				editButton.setData(sur.getId());
				editButton.addListener(new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						controller.getAppData().getLoaderLib().setUrl("EditSurvey/0/"+event.getButton().getData().toString() + "/");
					}
				});	
				editButton.setIcon(Config.ICON_SURVEYEDIT);
				editButton.setWidth("100px");
				
				// results button
				Button evaluationButton = new Button(TM.get("action.evaluate"));
				evaluationButton.setData(sur.getId());
				evaluationButton.addListener(new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						controller.getAppData().getLoaderLib().setUrl("Evaluation/0/0/"+event.getButton().getData().toString() + "/");
					}
				});
				evaluationButton.setIcon(Config.ICON_DETAILCHART);
				evaluationButton.setWidth("100px");
				
				// fillout button
				Button filloutButton = new Button(TM.get("action.participate"));
				filloutButton.setData(sur.getId());
				filloutButton.addListener(new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						if (sur.getRole().getId() == Config.COORDINATOR_ID) {
							controller.getAppData().getLoaderLib().setUrl("EditSurvey/1/"+event.getButton().getData().toString() + "/");
						} else {
							controller.getAppData().getLoaderLib().setUrl("EditSurvey/0/"+event.getButton().getData().toString() + "/");
						}
					}
				});
				filloutButton.setIcon(Config.ICON_EDIT);
				filloutButton.setWidth("100px");
				
				buttonBar.addComponent(filloutButton);
				buttonBar.addComponent(evaluationButton);
				buttonBar.addComponent(editButton);
				
				if (sur.getSurvey().getStage().getId() == Config.STAGE_SURVEY) {
					if (sur.getRole().getId() != Config.COORDINATOR_ID  && sur.getRole().getId() != Config.EXPERT_ID) {
						evaluationButton.setEnabled(false);
					}
				}
				
				if(sur.getRole().getId() != Config.COORDINATOR_ID) {
					buttonBar.removeComponent(editButton);
				}
				
				if(sur.getSurvey().getStage().getId() >= Config.STAGE_EVALUATION) {
					//buttonBar.removeComponent(filloutButton);
					filloutButton.setEnabled(false);
				}
				
				if(sur.getSurvey().getStage().getId() >= Config.STAGE_COMPLETED) {
					//buttonBar.removeComponent(filloutButton);
					editButton.setEnabled(false);
				}
				
				if(sur.getRole().getId() == Config.EXPERT_ID) {
					buttonBar.removeComponent(editButton);
					buttonBar.removeComponent(filloutButton);
				}
				
				return buttonBar;
			}
		});
		
		
		surveyTable.setContainerDataSource(controller.getTableContainer());
		
		surveyTable.setColumnHeader("surveyTitle", TM.get("dashboard.tab1.table.title"));
		surveyTable.setColumnHeader("surveyRole", TM.get("dashboard.tab1.table.role"));
		surveyTable.setColumnHeader("surveyCategory", TM.get("dashboard.tab1.table.category"));
		surveyTable.setColumnHeader("surveyCompletionDate", TM.get("dashboard.tab1.table.completion"));
		surveyTable.setColumnHeader("surveyStage", TM.get("dashboard.tab1.table.stage"));
		surveyTable.setColumnHeader("surveyEditButton", TM.get("action.actions"));
		surveyTable.setColumnHeader("surveyUniversity", TM.get("dashboard.tab1.table.university"));
		
		surveyTable.setVisibleColumns(new Object[]{"surveyTitle", "surveyRole", "surveyUniversity", "surveyStage", "surveyCompletionDate", "surveyEditButton"});
		
		surveyTable.setSortContainerPropertyId("surveyCompletionDate");
		surveyTable.setSortAscending(true); 
		
		surveyTable.setCellStyleGenerator(new Table.CellStyleGenerator() {
			public String getStyle(Object itemId, Object propertyId) {
				if (propertyId != null) {
					dashboardTableArgs dta = (dashboardTableArgs) itemId;
					String columnName = (String) propertyId;
					
					//Style Role column
					if (columnName.equals("surveyRole")) {
						return "role-style role"+dta.getSur().getRole().getId()+"";
					}
					
					//Style CompletioDate column
					if(columnName.equals("surveyCompletionDate")) {
						if (dta.getSur().getRole().getId() != Config.EXPERT_ID) {
							if (!controller.surveyFilledOut(dta.getSur()) && dta.getSur().getSurvey().getStage().getId() == Config.STAGE_SURVEY) {
								return "date-style date1";
							}
						}
					}
				}
				return null;
			}
		});
		
		return surveyTable;
	}

	@Override
	public void reBuild() {
		questionnaireTable.setContainerDataSource(controller.getQuestionaireData()); 
        questionnaireTable.setColumnHeader("title", TM.get("questionnaire.title"));
        questionnaireTable.setColumnHeader("desc", TM.get("questionnaire.desc"));
        questionnaireTable.setColumnHeader("createdAt", TM.get("questionnaire.created"));
        questionnaireTable.setColumnHeader("gen_edit", TM.get("action.edit"));
        questionnaireTable.setColumnHeader("gen_delete", TM.get("action.delete"));

        questionnaireTable.setVisibleColumns(
            new Object[]{
                "title", 
                "desc", 
                "createdAt", 
                "gen_edit", 
                "gen_delete"
            }
        );
		
	}

}
